import fs from 'fs'
import path, { dirname } from 'path'
import { fileURLToPath } from 'url'
import { v4 as uuid } from 'uuid'

/**
 * 扫描目录并生成树状结构
 * @param dirPath 要扫描的目录路径
 * @returns 树状结构的JSON对象
 */
const blackList = ['.DS_Store'] // 黑名单文件
function scanDirectory(dirPath: string, level: number = 0): DirectoryTree {
  const stats = fs.statSync(dirPath)
  // console.log('stats', stats)
  if (stats.isDirectory()) {
    const files = fs.readdirSync(dirPath)
    const children: DirectoryTree[] = files
      .filter((file) => {
        return !blackList.includes(path.basename(file))
      })
      .map((file) => {
        const fullPath = path.join(dirPath, file)
        return scanDirectory(fullPath, level + 1)
      })

    return {
      id: uuid(),
      name: path.basename(dirPath),
      type: 'directory',
      path: dirPath, // 添加path属性
      level, // 记录当前层级
      children
    }
  } else {
    return {
      id: uuid(),
      name: path.basename(dirPath),
      type: 'file',
      path: dirPath, // 添加path属性
      level // 记录当前层级
    }
  }
}

function main(filePath: string = '/webapp/src/views') {
  // const srcPath = path.join(__dirname, filePath)
  const __filename = fileURLToPath(import.meta.url)
  const __dirname = dirname(__filename)
  console.log('__filename', __filename)
  console.log('__dirname', __dirname)
  console.log('replace', process.env.NUXT_SCANE_REPLACE_PATH)
  const replacePath = process.env.NUXT_SCANE_REPLACE_PATH as string
  const srcPath = __dirname.replace(replacePath, '') + filePath
  console.log('后台项目目录————>', srcPath)
  try {
    const tree = scanDirectory(srcPath)
    // console.log('目录树结构:')
    // console.log(tree)
    return tree
  } catch (error) {
    console.error('扫描目录时出错:', error)
  }
}

export default main
